package com.monlyu.action.sql;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.monlyu.action.PageAction;
import com.monlyu.bean.Pages;
import com.monlyu.bo.SqlBo;

/**
 * http://localhost:8088/news/sql/SqlQuery!toInput.action
 */
public class SqlQueryAction extends PageAction {

	protected String defaultSorted() {
		return "-id";
	}

	private String sql;

	private String exportName;

	private InputStream exportInputStream;
	private SqlBo sqlBo;
	private Pages results;

	private static List eroroSql = new ArrayList(100);

	public void setSql(String sql) {
		this.sql = sql;
	}

	public String execute() {
		try {
			if (isErrorSql(sql)) {
				results = Pages.EMPTY;
			} else {
				results = sqlBo.getResultsBySql(sql.replaceAll(";", ""),
						getDefPage().getNo(), getDefPage().getSize());
			}
		} catch (RuntimeException e) {
			rememberError(sql);
			throw e;
		}
		return view("sqlQuery.jsp");
	}

	private static void rememberError(String sql) {
		if (eroroSql.size() > 99) {
			eroroSql.remove(99);
		}
		eroroSql.add(sql);
	}

	public String toInput() {
		results = Pages.EMPTY;
		return view("sqlQuery.jsp");
	}

	private static boolean isErrorSql(String sql) {
		return eroroSql.contains(sql);
	}

	public String getSql() {
		return sql;
	}

	public String getExportName() {
		return exportName;
	}

	public InputStream getExportInputStream() {
		return exportInputStream;
	}

	public Pages getResults() {
		return results;
	}

	public void setResults(Pages results) {
		this.results = results;
	}

	public void setSqlBo(SqlBo sqlBo) {
		this.sqlBo = sqlBo;
	}
}
